<?php
class BenchmarkUtil
{
    private static $timerLogs = [];

    /**
     * timer
     * @param  string $key
     * @return void
     */
    public static function timer($key = 'default')
    {
        if ($key === true) {
            return static::PrintTimerLogs();
        }
        if (!isset(self::$timerLogs[$key]['start'])) {
            self::$timerLogs[$key]['start'] = microtime(true);
        } else {
            self::$timerLogs[$key]['end'] = microtime(true);
            self::$timerLogs[$key]['cost'] = self::$timerLogs[$key]['end'] - self::$timerLogs[$key]['start'];
        }
    }

    public static function PrintTimerLogs(bool $withMemoryUsage = true)
    {

        foreach (self::$timerLogs as $key => $val) {
            printf('item:%s, start:%s, end:%s, cost:%s' . PHP_EOL, $key, $val['start'], $val['end'], $val['cost']);
        }
        $withMemoryUsage and printf('memory usage: %s,  memory peak usage:%s', static::memoryConvert(memory_get_usage(true)), static::memoryConvert(memory_get_peak_usage(true)));
    }

    public static function memoryConvert(numeric $size)
    {
        $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
        return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i];
    }
}
